package com.spring.mvc.util;

import java.math.BigDecimal;

import java.text.NumberFormat;

/**
 * 数字操作工具类
 * @author liujian
 *
 */
public class NumberUtil {
	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new RuntimeException(
					"The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

	}

	public static String formatNumber(double d, int scale) {
		return NumberFormat.getNumberInstance().format(round(d, scale));
	}

	public static String convertYuanString(long fenLong) {
		String fenString = "" + fenLong;
		if (fenString.length() < 3) {
			fenString = StringUtil.fillLeft(fenString, '0', 3);
		}
		return fenString.substring(0, fenString.length() - 2) + "."
				+ fenString.substring(fenString.length() - 2);
	}

	/**
	 * 将元表示的金额(允许小数点后两位)转为为分表示金额(长整型，无小数点)
	 * 
	 * @param yuanString
	 * @return
	 */
	public static long convertFenLong(String yuanString) {
		if (yuanString == null || "".equals(yuanString)) {
			return 0;
		} else {
			return (long) (round(Double.valueOf(yuanString), 2) * 100);
		}
	}
	
	public static long newConvertFenLong(String yuanString) {
		if (yuanString == null || "".equals(yuanString)) {
			return 0;
		} else {
			BigDecimal txnAt = new BigDecimal(yuanString).multiply(new BigDecimal(100));
			Long longTranAmt = txnAt.longValue();
			return (long)longTranAmt;
		}
	}

	public static String formatInt(int n) {
		if (n >= 10000000) {
			return formatNumber(n / 10000, 0) + "万";
		} else if (n >= 1000000) {
			return formatNumber(n / 10000, 0) + "万";
		} else if (n >= 100000) {
			return formatNumber(n / 10000, 0) + "万";
		} else if (n >= 10000) {
			return formatNumber(n / 10000, 0) + "万";
		} else if (n >= 1000) {
			return formatNumber(n / 1000, 0) +"千";
		} else {
			return "" + n;
		}
	}

}
